
import redis,json,random


class UserCache(object):

    def __init__(self, user_id):
        print("萨达", user_id)
        self.redis_con = redis.Redis(host='localhost', port=6379, password=123, db=2)
        self.max_ex = 10 * 60
        self.ex = 5 * 60
        self.key = 'user_%s'%user_id

    def if_user_data(self):
        try:
            json_data = self.redis_con.get(self.key)
            if json_data:
                return True
            else:
                return False
        except Exception:
            return False

    def get(self):
        try:
            json_data = self.redis_con.get(self.key)
            if not json_data:
                return None
            user_data = json.loads(json_data.decode())
            return user_data
        except Exception:
            return False

    def ex_time(self):
        try:
            ex = self.ex + random.randrange(0, self.max_ex)
            return ex
        except Exception:
            return False

    def add_redis(self,user_data):
        try:
            json_data = json.dumps(user_data)
            self.redis_con.set(self.key, json_data, ex=self.ex_time())
            return True
        except Exception as e:
            print("缓存》》", e)
            return False